<?php
class TdMySql extends TdRdbms {
	
	  function __construct($instance) {
	  	
		  	parent::__construct($instance);
		
		  	if ( !$this->connection ) {
		  		
			  	  if (empty($this->config)) {
			        	die("MySql instance not configured: ".$instance);
			  	  }

			  	  try
			  	  {
			  	    $dsn = "mysql:host=".$this->config['host'].";port=".$this->config['port'].";dbname=".$this->config['name'];
			  	    $options = array(
			  	  	  PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
			  	    );
			  	    $connection = new PDO($dsn, $this->config['username'], $this->config['password'], $options);
			  	    
			  	    $this->connection = $connection;
			  	  }
			  	  catch (PDOException $e) {
			  	    trigger_error($e->getMessage(), E_USER_ERROR);
			  	  }
		  	  
		  	}
	  	
	  }
	  
	  
	   
	  function close() {
	  	$this->connection = NULL;
	  }
	  
	  
	  function select($query) {
	  	$sql = "SELECT ".$query;	  	
	  	
	  	try {
    	  $rs = $this->connection->query($sql);
  	  	  $res = empty($rs) ? false : $rs->fetchAll(PDO::FETCH_ASSOC);
  	  	  if (!empty($rs)) {
  	  		  $rs->closeCursor();
  	  	  }
  	  	  else {
  	  		  trigger_error("No records found for [".$sql."]");
  	  	  }
	  	}
	  	catch (PDOException $e) {
	  		trigger_error($e->getMessage(), E_USER_ERROR);
	  	}
  	
	  	return $res;	 
	  }

	  function update($query) {
	  	$sql = "UPDATE ".$query;
	  	return $this->exec($sql);	  	
	  }
	  
	  
	  function insert($query) {
	  	$sql = "INSERT INTO ".$query;
	  	return $this->exec($sql);
	  	
	  }
	  
	  function delete($query) {
	  	$sql = "DELETE FROM ".$query;
	  	return $this->exec($sql);
	  }
  
    function exec($query) {
    	$res = false;
    	try {
    		//var_dump($query);
    		if ($this->connection->exec($query)) {
    			$res = true;
    		}
    	}
    	catch (PDOException $e) {
    		trigger_error($e->getMessage(), E_USER_ERROR);
    		$res = false;
    	}
    	
    	return $res;
    }
  
}
?>